package com.liangdemo.web.thread;

/**
 * 哲学家就餐问题
 *
 */
public class Test2 {
    class Chopsticks {

    }

    class Philosopher extends Thread {
        private Chopsticks left, right;
        private int index;

        public Philosopher(String name, int index, Chopsticks left, Chopsticks right) {
            this.setName(name);
            this.index = index;
            this.left = left;
            this.right = right;
        }

        public void run() {
            synchronized (left) {
                synchronized (right) {
                    System.out.println(index + "号 哲学家已经吃完");
                }
            }
        }
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        Chopsticks cs0 = test2.new Chopsticks();
        Chopsticks cs1 = test2.new Chopsticks();
        Chopsticks cs2 = test2.new Chopsticks();
        Chopsticks cs3 = test2.new Chopsticks();
        Chopsticks cs4 = test2.new Chopsticks();

        Philosopher p0 = test2.new Philosopher("p0", 0, cs0, cs1);
        Philosopher p1 = test2.new Philosopher("p1", 1, cs1, cs2);
        Philosopher p2 = test2.new Philosopher("p2", 2, cs2, cs3);
        Philosopher p3 = test2.new Philosopher("p3", 3, cs3, cs4);
        Philosopher p4 = test2.new Philosopher("p4", 4, cs4, cs0);
        p0.start();
        p1.start();
        p2.start();
        p3.start();
        p4.start();

    }
}
